package cn.tedu.file;
/**
 * @Author 金帮嘉诚  @Date 2021-06-17 周四 17:12
 */
/*本类用于拓展练习文件复制案例*/

import java.io.*;
import java.util.Scanner;

/**
 * 知识点：
 */
public class TestCopyFile {
    public static void main(String[] args) {
        //
        System.out.println("请输入源文件路径：");
        String source = new Scanner(System.in).nextLine();
        System.out.println("请输入目标文件路径：");
        String target = new Scanner(System.in).nextLine();
        copyFileWord(source, target);
//        copyFileStream(source, target);
    }

    public static void copyFileWord(String source, String target) {
        Reader in = null;
        Writer out = null;

        try {
            in = new BufferedReader(new FileReader(source));
//            out = new BufferedWriter(new FileWriter(target,true));
            out = new BufferedWriter(new FileWriter(target));

            int readable;
            while ((readable = in.read()) != -1) {
                out.write(readable);
            }
            System.out.println("恭喜您，文件复制成功！");
        } catch (Exception e) {
            System.out.println("很抱歉，文件复制失败！");
            e.printStackTrace();
        } finally {
            /*关流是有顺序的，如果有多个流，最后创建的流最先关闭
             * 多条关流语句需要各自try-catch
             * 没有正确写close()可能会导致复制失败*/
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    public static void copyFileStream(String source, String target) {
        InputStream in = null;
        OutputStream out = null;

        try {
            in = new BufferedInputStream(new FileInputStream(source));
            out = new BufferedOutputStream(new FileOutputStream(target, true));

            int readable;
            while ((readable = in.read()) != -1) {
                out.write(readable);
            }
            System.out.println("恭喜您，文件复制成功！");
        } catch (Exception e) {
            System.out.println("很抱歉，文件复制失败！");
            e.printStackTrace();
        } finally {
            /*关流是有顺序的，如果有多个流，最后创建的流最先关闭
             * 多条关流语句需要各自try-catch
             * 没有正确写close()可能会导致复制失败*/
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
